package cn.jhc;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

// import com.google.protobuf.compiler.PluginProtos.CodeGeneratorResponse.File;
import com.mysql.cj.xdevapi.Result;

@WebServlet("/admin/submit2.do")
@MultipartConfig(maxFileSize = 5368709120L)
public class Submit2Servlet extends HttpServlet{


    private static final Pattern FILE_PATTERN = Pattern.compile("filename=\"([^\"]*)\"");
    private static final Pattern FILE_SUFFIX_PATTERN = Pattern.compile("filename=\"[^\"]*(.[\\w]+)\"");
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = "";
        String sex = "";
        String hobbies = "";

        for (Part part : req.getParts()) {
            if (part.getName().equals("name")) {
                name = extractString(part);
            } else if (part.getName().equals("sex")) {
                sex = extractString(part);
            }else if (part.getName().equals("hobbies")) {
                hobbies += extractString(part);
            }
        }

        System.out.println("hobbies=" + hobbies + ",");
        System.out.println("name=" + name);
        System.out.println("sex=" + sex);

        String prefix = req.getServletContext().getRealPath("/uploads");
        Part filePart = req.getPart("portrait");
        String ctype = filePart.getHeader("Content-Type");
        String oriFilename = extractFilename(filePart.getHeader("Content-Disposition"));
        // String reFilename = new SimpleDateFormat("yyyy-mm-dd-hh:mm:ss").format(new Date()) + "-" + oriFilename;
        String reFilename = UUID.randomUUID().toString() + oriFilename;
        InputStream partInput = filePart.getInputStream();
        File destFile = new File(prefix + File.separator + reFilename);
        System.out.println(prefix);
        
        byte[] buffer = new byte[1024];
        FileOutputStream out = new FileOutputStream(destFile);
        int len = 0;
        while ((len = partInput.read(buffer)) != -1) {
            out.write(buffer);
        }

        Item item = new Item();
        item.setName(name);
        item.setSex(sex);
        item.setHobbies(hobbies);
        item.setOriginFilename(oriFilename);
        item.setReFilename(reFilename);
        item.setCtype(ctype);
        try {
            new DaoRu().save(item);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new ServletException(e);
        }

        
        resp.sendRedirect("/admin/list.html");
    }

    private String extractFilename(String disposition) {
        String filename = "not_found";
        Matcher matcher = FILE_PATTERN.matcher(disposition);
        if (matcher.find()) {
            filename = matcher.group(1);
        }
        return filename;
    }

    private String extractString(Part part) {
        String result = "";
        try {
            InputStream in = part.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = reader.readLine();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
}
